﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace MouseExtender.Controls.UserControls
{
    public partial class PopupUC : UserControl
    {
        private static int _openedPopupCount = 0;

        public static bool IsAnyPopupOpen
        {
            get
            {
                return _openedPopupCount == 0 ? false : true;
            }
        }

        public bool IsOpen
        {
            get
            {
                return popup.IsOpen;
            }
            set
            {
                popup.IsOpen = value;
            }
        }

        public UIElement Child
        {
            get
            {
                return placeholder.Child;
            }
            set
            {
                placeholder.Child = value;
            }
        }

        public static CustomPopupPlacementCallback Callback
        {
            get
            {
                return GetPlaces;
            }
        }

        public PopupUC()
        {
            InitializeComponent();
            popup.Closed += Popup_Closed;
            popup.Opened += Popup_Opened;
        }

        public static CustomPopupPlacement[] GetPlaces(Size popupSize, Size targetSize, Point offset)
        {
            MainWindow mainWindow = App.MainWindowInstance;
            double windowWidth = mainWindow.windowBackground.ActualWidth;
            double windowHeight = mainWindow.windowBackground.ActualHeight;
            double leftOffset = windowWidth < popupSize.Width ? (popupSize.Width - windowWidth) / -2 : (windowWidth - popupSize.Width) / 2;
            double topOffset = windowHeight < popupSize.Height ? (popupSize.Height - windowHeight) / -2 : (windowHeight - popupSize.Height) / 2;
            Point point = new Point(leftOffset, topOffset);
            CustomPopupPlacement placement = new CustomPopupPlacement(point, PopupPrimaryAxis.None);
            return new CustomPopupPlacement[] { placement };
        }

        private void Popup_MouseDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void Popup_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void Popup_Opened(object sender, EventArgs e)
        {
            _openedPopupCount++;
        }

        private void Popup_Closed(object sender, EventArgs e)
        {
            _openedPopupCount--;
        }

        private void popup_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (!App.MainWindowInstance.IsActive)
                App.MainWindowInstance.Activate();
        }
    }
}
